
from dvadmin.lowcode.models import Assets
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse
from django.core.cache import cache
import json

class AssetsSerializer(CustomModelSerializer):
    """
    区块-序列化器
    """

    class Meta:
        model = Assets
        fields = "__all__"
        read_only_fields = ["id"]
class AssetsViewSet(CustomModelViewSet):
    """
    物料管理
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = Assets.objects.all()
    serializer_class = AssetsSerializer
    def update(self, request, *args, **kwargs):
        cache.delete('assets_web')
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, request=request, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}
        return DetailResponse(data=serializer.data, msg="更新成功")

class NoautoAssetsViewSet(CustomModelViewSet):
    """
    物料获取-无需登入
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    # authentication_classes = []
    permission_classes = []
    queryset = Assets.objects.all()
    serializer_class = AssetsSerializer
    def list(self, request, *args, **kwargs):
        cacheName = "{}".format('assets_web')
        cachedata = cache.get(cacheName)
        if cachedata:
            return DetailResponse(data=cachedata, msg="获取成功")
        queryset = Assets.objects.get(is_use=1)
        serializer = self.get_serializer(queryset)
        data = json.loads(serializer.data['data'])
        cache.set(cacheName,data, timeout=86900)
        return DetailResponse(data=data, msg="获取成功")